<!-- 地图 -->
<template>
  <div id="map"></div>
</template>
<script>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import 'leaflet.markercluster/dist/MarkerCluster.css'
import 'leaflet.markercluster/dist/leaflet.markercluster'

import sdbj from '@/assets/json/sds.json' //山东省边界
import sdbjChild from '@/assets/json/sds1.json' //山东省包含子区域

import shuiku from '@/assets/json/reservoir.json' //水库
import skIcon from '@/assets/images/sq.png'
import { mapActions } from 'vuex'

export default {
  name: 'four-tubes',
  data () {
    return {
      map: null,
      geoJSONGroup: null,
      opacity: 1,
      countryLayer: null,
      county: '山东省',
      skLayerGroup: null
    }
  },
  mounted () {
    this.initMap()
  },

  methods: {
    ...mapActions({
      changetabImg: 'changetabImg'
    }),
    //初始化地图
    initMap () {
      //底图
      const image = L.tileLayer(
        'http://t{s}.tianditu.gov.cn/img_w/wmts?tk=55c172ba397d8de2a0259f800427e50d&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}',
        {
          subdomains: [0, 1, 2, 3, 4, 5, 6, 7]
        }
      )
      //注记
      const cia = L.tileLayer(
        'http://t{s}.tianditu.gov.cn/cia_w/wmts?tk=55c172ba397d8de2a0259f800427e50d&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}',
        {
          subdomains: [0, 1, 2, 3, 4, 5, 6, 7],
          transparent: true,
          zIndex: 3
        }
      )
      //天地图图组
      const tiandiMap = L.layerGroup([image, cia])

      //地图对象
      this.map = L.map('map', {
        crs: L.CRS.EPSG3857,
        center: [36.685807, 118.200923],
        maxZoom: 18,
        zoom: 7.8,
        minZoom: 2,
        attributionControl: false,
        doubleClickZoom: false,
        closePopupOnClick: true,
        layers: [tiandiMap],
        zoomSnap: 0.05,
        zoomControl: false,
        renderer: L.canvas({ padding: 1 })
      })
      const bounds = L.latLngBounds([
        [34.22, 122.43], // 下
        [38.23, 122.43], // 上
        [38.23, 114.19], // 左
        [34.22, 114.19] // 右
      ])
      //   this.map.setMaxBounds(bounds)
      this.addSK('临沂市')
      this.addLYBJ()
      this.addMask(sdbj)
    },
    //加载临沂边界json
    addLYBJ () {
      let that = this
      var countryLayer = L.geoJson(sdbjChild, {
        style: {
          weight: 3,
          opacity: this.opacity,
          color: '#0e75d8',
          fillOpacity: 0
        },
        onEachFeature: (feature, layer) => {
          // feature.geometry.getBounds().getCenter();
          layer.on({
            //鼠标移入方法
            mouseover: e => {
              var layer = e.target
              layer
                .setStyle({
                  weight: 3,
                  color: '#5601f3',
                  fillOpacity: 0.2
                })
                .bindPopup(`${feature.properties.name}`)
                .openPopup()

              if (!L.Browser.ie && !L.Browser.opera) {
                layer.bringToFront()
              }
            },
            //鼠标移出方法
            mouseout: e => {
              var layer = e.target
              layer.closePopup()

              layer.setStyle({
                color: '#0e75d8',
                fillOpacity: 0
              })
            }
          })
          //鼠标点击方法
          layer.on('click', e => {
            that.changetabImg(false)
            console.log('鼠标点击')
            var style = {
              weight: 3,
              opacity: 1,
              color: '#0e75d8',
              fillOpacity: 0
            }
            let feature = {
              features: [e.target.feature]
            }
            this.addMask(feature)
            this.countryLayer = L.geoJson(e.target.feature, { style: style })
            this.map.addLayer(this.countryLayer)
            this.map.fitBounds(this.countryLayer.getBounds())
            this.skLayerGroup.clearLayers()
            this.addSK()
          })
        }
      })
      this.geoJSONGroup = L.layerGroup([countryLayer])
      this.map.addLayer(this.geoJSONGroup)
    },
    //加载水库
    addSK (value) {
      //图标
      let that = this
      const myIcon = L.icon({
        iconUrl: skIcon,
        iconAnchor: [10, 41],
        iconSize: [20, 20]
      })
      var skLayer = L.geoJSON(shuiku, {
        pointToLayer: function (feature, latlng) {
          if (Number(feature.id) < 20) {
            const marker = L.marker(latlng, { icon: myIcon }).bindPopup(
              `
              <div>水库编码：${feature.properties.re_id}</div>
              <div>水库名称：${feature.properties.re_name}</div>
              <div>所属区县：${feature.properties.county}</div>
              <div>所属乡镇：${feature.properties.country}</div>
              <div>水库类型：${feature.properties.re_type}</div>
              <div>水库规模：${feature.properties.re_scale}</div>
            `
            )
            marker.on('click', function (e) {
              // 点击marker点事件
              console.log(e)
              //   that.$router.push('/ProjectHome/index/cityoverview')
              that.$router.push('/prodetail')
            })
            return marker
          }
        }
      })
      this.skLayerGroup = L.markerClusterGroup({
        maxClusterRadius: 80,
        disableClusteringAtZoom: 14,
        iconCreateFunction: function (cluster) {
          return L.divIcon({
            html:
              '<div style="position: relative"><img style="width:20px;height:20px; z-index:-1" src="' +
              skIcon +
              '">' +
              '<p style="position: relative; font-size: 14px; font-weight: bold; color: white; margin-top: -6px;margin-left: 4px;">' +
              cluster.getChildCount() +
              '</p>' +
              '</div>',
            // cluster.getChildCount() +
            iconSize: L.point(20, 20),
            className: 'marker-cluster'
          })
        }
      })
      this.skLayerGroup.on('clusterclick', e => {
        let a = e.sourceTarget
        console.log(a.getAllChildMarkers())
        console.log([...a._markers])
        console.log(
          e.sourceTarget.getAllChildMarkers()[0].feature.properties,
          '聚合点击事件'
        )
      })
      this.skLayerGroup.addLayer(skLayer)
      this.map.addLayer(this.skLayerGroup)
    },
    //添加遮罩
    addMask (data) {
      //遮罩层遮蔽层,geojson分两种情况
      let that = this
      var latlngs
      var feature = data['features'][0].geometry.coordinates
      if (feature[0][0][0] instanceof Array) {
        latlngs = feature[0]
      } else {
        latlngs = feature
      }

      var pNW = { lat: -180.0, lng: 180.0 }
      var pNE = { lat: 180, lng: 180.0 }
      var pSE = { lat: 180.0, lng: -180.0 }
      var pSW = { lat: -180.0, lng: -180.0 }
      //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
      var pArray = []
      pArray.push(pNW)
      pArray.push(pNE)
      pArray.push(pSE)
      pArray.push(pSW)
      pArray.push(pNW)
      //循环添加各闭合区域
      for (var i = 0; i < latlngs.length; i++) {
        var points = []
        for (var key in latlngs[i]) {
          if (latlngs[i].hasOwnProperty(key)) {
            var value = latlngs[i][key]
            points.push({ lat: Number(value[1]), lng: Number(value[0]) })
          }
        }
        //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
        pArray = pArray.concat(points)
        pArray.push(pArray[0])
      }
      //反向遮蔽层
      var ahLayer = L.polygon(pArray, {
        color: 'transparent',
        fillColor: '#22354d',
        fillOpacity: 0.9
      })
      ahLayer.on('dblclick', e => {
        that.changetabImg(true)
        this.zhezhaoGroup.clearLayers()
        this.skLayerGroup.clearLayers()
        this.countryLayer.clearLayers()
        this.addMask(sdbj)
        this.addSK('临沂市')
        this.addLYBJ()

        this.map.setView([36.685807, 118.200923], 7.8)
      })
      //建立多边形覆盖物
      this.zhezhaoGroup = L.layerGroup([ahLayer])
      this.map.addLayer(this.zhezhaoGroup)
    }
  }
}
</script>
<style lang="scss" scoped>
#map {
  height: 100%;
  width: 100%;
}
::v-deep .leaflet-popup-content-wrapper,
::v-deep .leaflet-popup-tip {
  border: 1px solid #4ce0db;
  background-color: rgba($color: #1253b6, $alpha: 0.8);
  color: #fff;
}
::v-deep .leaflet-popup-tip {
  position: fixed;
  border-left: transparent;
  border-top: transparent;
  left: 50%;
  bottom: 0;
  margin-left: -13px;
  margin-bottom: -7px;
  box-shadow: none;
  background-color: rgba($color: #1253b6, $alpha: 0.8);
}

::v-deep .leaflet-popup-content {
  .popbox {
    .poptitle {
      .titlebox {
        display: flex;
        align-items: center;
        justify-content: space-between;

        div {
          font-size: 16px;
          line-height: 16px;

          &:nth-child(2) {
            cursor: pointer;
          }
        }
      }

      p {
        background-color: #37f3ff;
        margin: 8px 0 6px -19px;
        width: 90px;
        height: 1px;
      }
    }

    .content {
      div {
        font-size: 14px;
        line-height: 14px;
        padding: 6px 0;
      }
    }
  }
}
::v-deep .leaflet-popup-close-button {
  // color: #fffbfb !important;
  display: none;
}
</style>
